import {getCookie} from "h3";
import {getRefreshTokenByToken} from "~/server/db/refreshTokens.js";
import {decodeRefreshToken} from "~/server/utils/jwt.js";
import {getUserById} from "~/server/db/users.js";
export default defineEventHandler(async (event) => {
    const refreshToken = getCookie(event,'refresh_token') //从http cookie里面取的
    if(!refreshToken){
        return sendError(event, createError({
            statusCode: 401,
            statusMessage: 'Refresh token is invalid'
        }))
    }
    //核心： 通过refreshToken 从数据库中拿到 RefreshToken模型对应的数据  （登陆的时候有关联）
    const rToken = await getRefreshTokenByToken(refreshToken)
    if (!rToken) {
        return sendError(event, createError({
            statusCode: 401,
            statusMessage: 'Refresh token is invalid'
        }))
    }
    // 验证refreshToken 通过解码拿到userId
    const token = decodeRefreshToken(refreshToken)

    try {
        // 最后通过userid 拿到最新token 返回回去
        const user = await  getUserById(token.userId)
        const { accessToken } = generateTokens(user)
        return { access_token: accessToken }
    }catch (e){
        return sendError(event, createError({
            statusCode: 500,
            statusMessage: 'Something went wrong'
        }))
    }
})